package cn.edu.xjtu.nbrash.xbarsuite.floatbutton;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import cn.edu.xjtu.nbrash.xbarsuite.R;
import cn.edu.xjtu.nbrash.xbarsuite.RashIntents;
import cn.edu.xjtu.nbrash.xbarsuite.floatbutton.FloatButtonService.FloatButtonStatus;
import cn.edu.xjtu.nbrash.xbarsuite.utilities.Utilities;

public class RashCropActivity extends Activity {

	@SuppressWarnings("unused")
	private static final String TAG = RashCropActivity.class.getName();

	public static final String ACTION_CROP = "cn.edu.xjtu.nbrash.xbarsuite.CROP";

	private static final int RC_CROP = 0x1010;

	private int retry;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rash_crop);

		Intent intent = getIntent();
		if (ACTION_CROP.equals(intent.getAction())) {
			Uri data = intent.getData();
			retry = intent.getIntExtra(FloatButtonService.EXTRA_RETRY, 0);
			retry++;
			if (data != null) {
				crop(data);
			} else {
				finish();
			}
		} else {
			finish();
		}
	}

	private void crop(Uri data) {
		Intent intent = new Intent();
		intent.setAction(RashIntents.Image.ACTION_CROP);
		// 设置图片URI, 类型为"image/*"
		intent.setDataAndType(data, RashIntents.Image.TYPE_IMAGE);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("scale", true);
		intent.putExtra("scaleUpIfNeeded", true);
		intent.putExtra("return-data", true);
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("tips", "请把二维码放在识别框中");
		startActivityForResult(intent, RC_CROP);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case RC_CROP:
					String tempPath = getFilesDir().getPath() + "temp.crop.png";
					Bitmap bitmap = data.getParcelableExtra("data");
					Uri uri = Utilities.bitmap2Uri(tempPath, bitmap);
					Intent intent = new Intent(this, FloatButtonService.class);
					intent.setAction(FloatButtonService.ACTION_DECODER);
					intent.setData(uri);
					intent.putExtra(FloatButtonService.EXTRA_RETRY, retry);
					startService(intent);
					finish();
					break;
			}
		} else {
			FloatButtonService.setStatus(FloatButtonStatus.Idle);
			Toast.makeText(this, "用户取消！", Toast.LENGTH_SHORT).show();
			finish();
		}
	}
}
